import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { CLRequestHook, CLRequestConfig } from './type'
import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'

//loading初始化是否展示
const DEFAULT_LOADING = false

class CLRequest {
  instance: AxiosInstance
  interceptors?: CLRequestHook
  showLoading: boolean
  loading?: LoadingInstance

  constructor(config: CLRequestConfig) {
    this.instance = axios.create(config)
    this.showLoading = config.showLoading ?? DEFAULT_LOADING
    this.interceptors = config.interceptors

    this.instance.interceptors.request.use(
      this.interceptors?.requestHook,
      this.interceptors?.requestHookCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseHook,
      this.interceptors?.responseHookCatch
    )

    // 添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在请求数据...',
            background: 'rgba(0,0,0,0.5)'
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        //移除loading
        this.loading?.close()

        return res.data
      },
      (err) => {
        this.loading?.close()

        return err
      }
    )
  }

  request<T>(config: CLRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestHook) {
        config = config.interceptors.requestHook(config)
      }
      if (config.showLoading) {
        this.showLoading = config.showLoading
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseHook) {
            res = config.interceptors.responseHook(res)
          }
          //将shouloading设置true 这样不会影响下一个请求
          this.showLoading = DEFAULT_LOADING
          resolve(res)
        })
        .catch((err) => {
          this.showLoading = DEFAULT_LOADING
          reject(err)
          return err
        })
    })
  }
  get<T>(config: CLRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }

  post<T>(config: CLRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }

  delete<T>(config: CLRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }

  patch<T>(config: CLRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}
export default CLRequest
